<template>
  <div class="container">
    <!-- 上方盒子 -->
    <div class="upper-box">
      <div class="book-img">
        <img
            id="bookCover"
            :alt="book.bookName"
            :src="`${imgBaseUrl}` + `${book.picUrl}`"
            class="cover"
        />
      </div>
      <div class="book-info">
        <div class="book-title">
          <div class="book-name">{{ book.bookName }}</div>
          <div class="book-author">{{ book.authorName }}</div>
        </div>
        <div class="book-intro">
          <ul>
            <li>
              <span class="item">类别：<em>{{ book.categoryName }}</em></span>
            </li>
            <li>
              <span class="item">状态：<em>{{ book.bookStatus == 0 ? "连载中" : "已完结" }}</em></span>
            </li>
            <li>
              <span class="item">总点击：<em id="cTotal">{{ book.visitCount }}</em></span></li>
            <li>
              <span class="item">总字数：<em>{{ book.wordCount }}</em></span>
            </li>
          </ul>

        </div>
        <div class="book-desc">
          <!--          <p style="white-space:break-spaces;line-height: 30px" v-html="book.bookDesc"></p>-->
          <p class="desc-content" v-html="descContent"></p>
          <div v-if="showBtn" class="show-btn" @click="toggleContent">
            <span>{{ isCollapsed ? '∨ 展开' : '∧ 收起' }}</span>
          </div>
        </div>
        <div class="book-btn">
          <el-button round @click="bookContent(book.id, book.firstChapterId)">点击阅读</el-button>
        </div>
      </div>

    </div>

    <!-- 下方盒子 -->
    <div class="lower-box">
      <!-- 左侧大盒子 -->
      <div class="left-big-box">
        <div class="left-item1">
          <div class="title">
            <div class="tit1">最新章节<span id="bookIndexCount">({{ chapterAbout.chapterTotal }}章)</span></div>
            <div class="tit2" @click="chapterList(book.id)">全部目录</div>
          </div>
          <div class="chapter">
            <div class="top">
              <div v-if="chapterAbout.chapterInfo" class="name" @click="bookContent(
                    chapterAbout.chapterInfo.bookId,
                    chapterAbout.chapterInfo.id
                    )">{{ chapterAbout.chapterInfo.chapterName }}
              </div>
              <div v-if="chapterAbout.chapterInfo" class="time">
                更新时间：{{ chapterAbout.chapterInfo.chapterUpdateTime }}
              </div>
            </div>
            <div class="content">
              <span v-html="`${chapterAbout.contentSummary}` + '...'"></span>
            </div>
          </div>
        </div>
        <div class="left-item2">
          <div class="top">
            <div class="title">
              <div class="left">作品评论区 <span>({{ newestComments.commentTotal }}条)</span></div>
              <div class="right" @click="scrollToElement(submitRef)">发表评论</div>
            </div>
            <div v-if="newestComments.commentTotal == 0" class="content1">
              <img :src="no_comment" alt=""/>
              <div class="no-comment">
                暂无评论
              </div>
            </div>
            <div v-else class="content2">
              <div v-for="(item, index) in newestComments.comments" :key="index" class="comment-item">
                <div class="header-img">
                  <img :src="item.commentUserPhoto?imgBaseUrl + item.commentUserPhoto:man" alt=""/>
                </div>
                <div class="item-detail">
                  <div class="detail-top">{{ item.commentUser }}</div>
                  <div class="detail-center" v-html="item.commentContent"></div>
                  <div class="detail-bottom">
                    <div class="time">{{ item.commentTime }}</div>
                    <div v-if="item.commentUserId == uid" class="modify">
                      <span @click="updateUserComment(item.id, item.commentContent)">修改</span>
                      <span>&nbsp;|&nbsp;</span>
                      <span @click="deleteUserComment(item.id)">删除</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <el-dialog
                v-model="dialogUpdateCommentFormVisible"
                title="评论修改"
            >
              <el-form>
                <el-form-item label="评论内容">
                  <el-input v-model="updComment" type="textarea"/>
                </el-form-item>
              </el-form>
              <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="dialogUpdateCommentFormVisible = false"
                    >取消</el-button
                    >
                    <el-button type="primary" @click="goUpdateComment">确定</el-button>
                  </span>
              </template>
            </el-dialog>
            <div class="comment-more">
              <span @click="getAllComments(book.id)">查看全部评论></span>
            </div>
          </div>
          <div class="bottom">
            <div class="title">
              <div>发表评论</div>
            </div>
            <div id="target" ref="submitRef" class="comment-submit">
              <textarea
                  v-if="uid"
                  id="txtComment"
                  v-model="commentContent"
                  class="replay_text"
                  cols="20"
                  maxlength="150"
                  name="txtComment"
                  placeholder="我来说两句..."
                  rows="2"></textarea>
              <div v-if="uid" class="reply">
                <div class="comment-tag"><em>{{ commentContent.length }}/150</em>&nbsp;字</div>
                <div>
                  <el-button class="reset-btn" round @click="userCommentReset">清空</el-button>
                  <el-button class="reply-btn" round @click="userComment">发表</el-button>
                </div>

              </div>
              <div v-else class="comment-login">
                如需评论请先<a href="/login">登录</a>或<a href="/register">注册</a>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧小盒子组 -->
      <div class="right-box-group">
        <div class="right-small-box1">
          <div class="author-head">
            <img :src="author_head" class="author-img">
            <div class="author-type">签约作家</div>
            <div class="author-name" @click="searchByK(book.authorName)">{{ book.authorName }}</div>
          </div>
          <div class="author-talk">
            <h4>作者有话说</h4>
            <div>
              亲亲们，你们的支持是我最大的动力！求点击、求推荐、求书评哦！
            </div>
          </div>

        </div>
        <div class="right-small-box2">
          <div class="title">同类推荐</div>
          <div v-for="item in books" :key="item.id" class="item">
            <img :alt="item.bookName" :src="`${imgBaseUrl}` + `${item.picUrl}`" class="book-img"
                 @click="bookDetail(item.id)">
            <div class="info">
              <div class="book-name" @click="bookDetail(item.id)">{{ item.bookName }}</div>
              <div class="book-desc" @click="bookDetail(item.id)"
                   v-html="item.bookDesc.length>58?item.bookDesc.substring(0,58)+'...':item.bookDesc"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {comment, deleteComment, updateComment} from "@/api/user";
import {ElMessage} from "element-plus";
import {
  addVisitCount,
  getBookById,
  getLastChapterAbout,
  listNewestComments,
  listRecBooks,
  listAllComments
} from "@/api/book";
import {onMounted, onUpdated, reactive, type Ref, ref, toRefs} from "vue";
import {useRoute, useRouter} from "vue-router";
import {useAuthStore} from "@/stores/auth";
import type {Book, ChapterAbout, Comments} from "@/type/book";
import author_head from "@/assets/images/author_head.png";
import no_comment from "@/assets/images/no_comment.png";
import man from "@/assets/images/man.png";
import emitter from "@/utils/bus";
import {useSearchStore} from "@/stores/search";

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const serachStore = useSearchStore();
const submitRef = ref(null);
const state = reactive({
  uid: authStore.getUid(),
  book: {} as Book,
  books: [] as Book[],
  chapterAbout: {} as ChapterAbout,
  commentContent: "",
  newestComments: {} as Comments,
  imgBaseUrl: import.meta.env.VITE_APP_BASE_IMG_URL,
  dialogUpdateCommentFormVisible: false,
  commentId: "",
  updComment: "",
  showBtn: false,
  descContent: '',
  maxlength: 121,
  isCollapsed: true
});
//解构state
const {
  uid,
  book,
  imgBaseUrl,
  showBtn,
  descContent,
  maxlength,
  isCollapsed,
  chapterAbout,
  books,
  newestComments,
  commentContent,
  dialogUpdateCommentFormVisible,
  updComment
} = toRefs(state);

const toggleContent = () => {
  if (!isCollapsed.value) {
    descContent.value = book.value.bookDesc.substring(0, maxlength.value) + "...";
  } else {
    descContent.value = book.value.bookDesc
  }
  isCollapsed.value = !isCollapsed.value;
}
onMounted(async () => {
  const bookId = route.params.id;
  await loadBook(bookId);
  await loadRecBooks(bookId);
  await loadLastChapterAbout(bookId);
  await loadNewestComments(bookId);

});

onUpdated(() => {
  // 对于支持`scroll-behavior`的现代浏览器，使用平滑滚动效果
});

const loadBook = async (bookId: any) => {
  const {data} = await getBookById(bookId);
  state.book = data;
  if (state.book.bookDesc.length > maxlength.value) {
    state.descContent = state.book.bookDesc.substring(0, maxlength.value) + "...";
    isCollapsed.value = true
    showBtn.value = true
  } else {
    isCollapsed.value = false
    state.descContent = state.book.bookDesc
  }
  await addBookVisit(bookId);
};

const loadRecBooks = async (bookId: any) => {
  const {data} = await listRecBooks({bookId: bookId});
  state.books = data;
};

const loadLastChapterAbout = async (bookId: any) => {
  const {data} = await getLastChapterAbout({bookId: bookId});
  state.chapterAbout = data;
};

const bookContent = (bookId: any, chapterId: any) => {
  router.push({path: `/book/${bookId}/${chapterId}`});
};

const bookDetail = async (bookId: any) => {
  window.scrollTo({top: 0, behavior: 'smooth'});
  router.push({path: `/book/${bookId}`});
  await loadBook(bookId);
  await loadRecBooks(bookId);
  await loadLastChapterAbout(bookId);
  await loadNewestComments(bookId);
};

const chapterList = (bookId: any) => {
  router.push({path: `/chapter_list/${bookId}`});
};

const addBookVisit = async (bookId: any) => {
  await addVisitCount({bookId: bookId});
};

const loadNewestComments = async (bookId: any) => {
  const {data} = await listNewestComments({bookId: bookId});
  state.newestComments = data;
};
const getAllComments = async (bookId: any) => {
  const {data} = await listAllComments({bookId: bookId});
  ElMessage.success("获取评论成功！");
  state.newestComments = data;
}
const userComment = async () => {
  if (!state.commentContent) {
    ElMessage.error("用户评论不能为空！");
    return;
  }
  if (state.commentContent.length < 10) {
    ElMessage.error("评论不能少于 10 个字符！");
    return;
  }
  if (state.commentContent.length > 512) {
    ElMessage.error("评论不能多于 512 个字符！");
    return;
  }
  await comment({
    bookId: state.book.id,
    commentContent: state.commentContent,
  });
  ElMessage.success("评论成功！");
  state.commentContent = "";
  await loadNewestComments(state.book.id);
};
const userCommentReset = async (id: any) => {
  state.commentContent = "";
};
const updateUserComment = (id: any, comment: any) => {
  state.dialogUpdateCommentFormVisible = true;
  state.updComment = comment;
  state.commentId = id;
};

const deleteUserComment = async (id: any) => {
  alert(id)
  await deleteComment(id);
  await loadNewestComments(state.book.id);
};

const goUpdateComment = async (id: any) => {
  state.dialogUpdateCommentFormVisible = false;
  await updateComment(state.commentId, {commentContent: state.updComment});
  ElMessage.success("评论更新成功！");
  await loadNewestComments(state.book.id);
};
const searchStore = useSearchStore();
const searchByK = (key: any) => {
  router.push({path: "/book_class", query: {key: key}});
  searchStore.setSerachKey(key)
};

function scrollToElement(element: any) {
  if (element) {
    // 使用vue-use库进行平滑滚动
    scrollTo(0, element.offsetTop);
  }
}
</script>
<style lang="scss" scoped>
.container {
  box-sizing: border-box;
  background-color: #F5F5F5;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  //height: 100vh; /* 设置容器高度为视窗高度 */
  .upper-box {
    margin: 0 auto;
    width: 60%;
    background-color: #fff;
    box-sizing: border-box;
    padding: 10px;
    //flex: 1; /* 按照剩余空间自适应高度 */
    margin-bottom: 10px;
    display: flex;

    .book-img {
      /*图片宽度和高度调整*/
      width: 180px;
      height: 200px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .book-info {
      padding-left: 10px;
      display: flex;
      flex-direction: column;
      width: 100%;

      .book-title {
        width: 100%;
        //border: 1px solid #000;
        display: flex;

        .book-name {
          font-size: 25px;
          font-weight: 500;
          //border: 1px solid #000;
        }

        .book-author {
          font-size: 14px;
          //border: 1px solid #000;
          //底部对齐
          align-self: flex-end;
          padding-left: 20px;
          color: #464646;
        }
      }

      .book-intro {
        //border: 1px solid #000;
        ul {
          display: flex;
          //justify-content: space-between; /* 水平间距相等 */
          list-style-type: none;
          padding: 20px 0;
          gap: 40px;

          li {
            color: #666665;

            em {
              //斜体
              font-style: italic;
            }
          }
        }


      }

      .book-desc {
        .desc-content {
          white-space: break-spaces;
          line-height: 30px;
        }

        .show-btn {
          float: right;
          color: #3179CB;

          &:hover {
            cursor: pointer;
            color: #fc7403;

          }
        }
      }

      .book-btn {
        padding-top: 10px;

        .el-button {
          width: 120px;
          background-color: #FA8121; /* 设置橙色背景 */
          color: white; /* 设置白色字体 */
          padding: 20px 20px; /* 根据需要调整内边距以适应椭圆形状 */
          font-size: 14px; /* 字体大小可以根据需求调整 */
        }
      }
    }
  }

  .lower-box {
    box-sizing: border-box;
    width: 60%;
    margin: 0 auto;
    display: flex;
    gap: 10px;
    flex: 1; /* 同样按剩余空间自适应高度 */
    .left-big-box {
      //border: 1px solid #000;
      background-color: #fff;
      flex: 1; /* 占据剩余宽度 */
      padding: 20px;
      display: flex;
      flex-direction: column;

      div {
        display: flex;
        justify-content: space-between;
      }

      .left-item1 {
        display: flex;
        flex-direction: column;

        .title {
          width: 100%;
          display: flex;
          justify-content: space-between;
          border-bottom: 1px solid #e3dfdf;

          .tit1 {
            font-size: 20px;
            padding-bottom: 20px;

            #bookIndexCount {
              font-size: 14px;
              align-self: flex-end;
              padding-left: 10px;
              color: #666767;
            }

          }

          .tit2 {
            font-size: 14px;

            &:hover {
              cursor: pointer;
              color: #fc7403;
            }
          }
        }

        .chapter {
          display: flex;
          flex-direction: column;

          .top {
            width: 100%;
            display: flex;
            justify-content: space-between;
            padding-top: 10px;

            .name {
              padding: 10px 0;
              font-size: 20px;
            }

            .time {
              font-size: 20px;
              padding: 10px 0;
              color: #9D9FB1;
            }
          }

          .content {
            padding: 10px 0;
            color: #B2B2B2;
            font-size: 14px;
          }
        }

      }

      .left-item2 {
        display: flex;
        flex-direction: column;

        .top {
          width: 100%;
          //border: 1px solid #000;
          padding: 10px 0;
          display: flex;
          flex-direction: column;

          .title {
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #e3dfdf;
            padding-bottom: 10px;

            .left {
              font-size: 20px;

              span {
                font-size: 14px;
                padding-left: 10px;
                align-self: flex-end;
                color: #63615F;
              }
            }

            .right {
              font-size: 14px;

              &:hover {
                cursor: pointer;
                color: #fc7403;
              }
            }
          }

          .content1 {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            //border: 1px solid red;
            height: 560px;

            img {
              width: 100px;
              object-fit: cover;
              //margin: 160px auto 0;
            }

            .no-comment {
              font-size: 18px;
              color: #CCCCCC;
              margin: 0 auto;
              //margin-bottom: 160px;
            }
          }

          .content2 {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            //border: 1px solid red;
            height: 560px;
            overflow: scroll;
            overflow-x: hidden;

            .comment-item {
              width: 100%;
              display: flex;
              border-bottom: 1px solid #e3dfdf;
              padding: 20px 0;
              justify-content: flex-start;
              box-sizing: border-box;

              .header-img {
                //width: 50px;
                //height: 50px;
                //圆形
                img {
                  width: 50px;
                  height: 50px;
                  object-fit: cover;
                  border-radius: 50%;
                }

              }

              .item-detail {
                width: 100%;
                display: flex;
                gap: 10px;
                padding-left: 20px;
                flex-direction: column;

                .detail-top {
                  font-size: 14px;
                }

                .detail-center {
                  line-height: 20px;
                  font-size: 14px;
                }

                .detail-bottom {
                  font-size: 12px;
                  color: #98A4A4;

                  span {
                    &:hover {
                      cursor: pointer;
                      color: #fc7403;
                    }
                  }
                }
              }
            }

            .comment-item:last-child {
              border-bottom: none;
            }


          }

          .comment-more {
            //width: 100%;
            //border: 1px solid #000;
            background-color: #F7F7F7;
            justify-content: center;
            padding: 10px;

            span {
              &:hover {
                cursor: pointer;
                color: #fc7403;
              }
            }
          }
        }

        .bottom {
          display: flex;
          flex-direction: column;

          .title {
            font-size: 18px;
            //border: 1px solid #000;
            padding: 10px 0;
          }

          .comment-submit {
            //border: 1px solid #000;
            display: flex;
            flex-direction: column;

            .comment-login {
              padding: 30px 0;
              justify-content: center;
            }

            textarea {
              height: 120px;
              resize: none;
              padding: 10px;
              border: 1px solid #ccc;
              border-radius: 5px;
              font-size: 14px;
              box-sizing: border-box;
              outline: none;
              box-shadow: 0px 5px 30px rgba(0, 0, 0, 0.1);
            }

            .reply {
              padding: 10px 0;

              .comment-tag {
                em {
                  font-style: normal;
                }
              }

              .reset-btn {
                background-color: grey;
                width: 100px;
                height: 40px;
                color: #fff;
              }

              .reply-btn {
                background-color: #fc7403;
                width: 100px;
                height: 40px;
                color: #fff;
              }
            }
          }
        }
      }

    }

    .right-box-group {
      display: flex;
      gap: 10px;
      flex-direction: column;
      width: 25%; /* 或者使用固定像素值，比如width: 300px; */
      margin-left: auto; /* 让它自动靠右对齐 */
      .right-small-box1 {
        background-color: #fff;
        //border: 1px solid #000;
        padding: 10px;
        //flex: 1; /* 两个小盒子在竖直方向上均分空间 */
        display: flex;
        flex-direction: column;

        .author-head {
          width: 90%;
          padding: 10px;
          margin: 0 auto;
          text-align: center;
          left: 0;
          top: 0;

          .author-type {
            margin: 0 auto;
            width: 80px;
            position: relative;
            bottom: 10px;
            background-color: #F96F22;
            padding: 2px;
            color: #FFFFFF;
          }

          .author-name {
            clear: both;
            font-size: 12px;

            &:hover {
              cursor: pointer;
              color: #fc7403;
            }
          }

          border-bottom: 1px solid #e3dfdf;
        }

        .author-talk {
          padding: 10px 0 30px 0;
          line-height: 30px;
          font-size: 14px;
        }
      }

      .right-small-box2 {
        background-color: #fff;
        //border: 1px solid #000;
        padding: 20px;
        flex: 1; /* 两个小盒子在竖直方向上均分空间 */
        display: flex;
        flex-direction: column;

        .title {
          font-size: 18px;
          font-weight: bold;
          padding-bottom: 10px;
          border-bottom: 1px solid #e3dfdf;
        }

        .item {
          display: flex;
          padding: 10px 0;
          border-bottom: 1px solid #e3dfdf;

          img {
            width: 80px;
            height: 120px;
            object-fit: cover;

            &:hover {
              cursor: pointer;
              border: 1px solid red;
            }
          }

          .book-name {
            padding-left: 10px;
            font-size: 16px;
            font-weight: bold;
            line-height: 20px;

            &:hover {
              cursor: pointer;
              color: #fc7403;
            }
          }

          .book-desc {
            padding-left: 10px;
            padding-top: 10px;
            font-size: 12px;
            line-height: 20px;

            &:hover {
              cursor: pointer;
              color: #fc7403;
            }
          }
        }

        .item:last-child {
          border: none;
          padding-bottom: 0;
        }
      }
    }
  }


}


</style>